<?php
namespace Admin\Controller;
use Think\Controller;
use Admin\Model\managerModel;
use Admin\Model\configModel;
use Admin\Model\tmplModel;
use Admin\Model\roleModel;
use Admin\Model\purviewsModel;

class BaseController extends Controller{

    public $uid;
    public $adminuid;
    public $admininfo;
    public $managerModel;
    public $configModel;
    public $tmpl;
    public $menuModel;
    public $no_need_login = array(
        "finance/countyeji",
        "login/*"
    );//不需要登录的控制器,*匹配所有action

    public function __construct() {

        $this->_getConfig();//获取配置文件
        //读取模板id并缓存
        //TODO
        $tmpl = S("TMPL");
        if(empty($tmpl) || 1){
            $tmpl = $this->_getTmpId();//获取模板id
            S("TMPL",$tmpl);
        }
        $this->tmpl = $tmpl;
        

        parent::__construct();
        $this->menuModel = new \Admin\Model\menuModel();
        $this->managerModel = new managerModel();
        $this->uid = session('adminuid');
        $this->admininfo = session('admininfo');
        $this->assign("admininfo",$this->admininfo);
        $this->updateManagerSession($this->uid);//获取最新的用户信息
        $this->_checkLogin();//检查登录
        $controller = strtolower(CONTROLLER_NAME);//转成小写
        $action = strtolower(ACTION_NAME);//转成小写
        $this->assign('action',$action);
        $this->assign('controller',$controller);
        //获取菜单
        //获取一级菜单
        //当前角色
//        $role_id = $this->admininfo['role_id'];
//
//        $roleModel = new roleModel();
//        $where = array(
//            "role_id" => $role_id
//        );
//        if($role_id){
//            $quanxian = $roleModel->getRole($where);
//            if($quanxian){
//               $purviews = $quanxian['purviews'];
//               //获取一级菜单
//               if($purviews){
//                   $purviewsModel = new purviewsModel();
//                   $where_p = array(
//                       "gid" => 0,
//                       "id" => array("IN",$purviews)
//                   );
//                   $plist = $purviewsModel->getPurviewsList($where_p);
//                   $this->assign("topmenu",$plist);
//               }
//
//            }
//        }

        if(!IS_AJAX){
            layout('Common/layout');
        }
    }

    //获取数据库中的配置文件
    protected function _getConfig(){
        $this->configModel = new configModel();
        $where = array(
            "status" => 1,
        );
        $res = $this->configModel->getConfigList($where);
        if(!empty($res)){
            foreach($res as $k=>$v){
                C($v['cname'],$v['cvalue']);
            }
        }
        return true;
    }

    //获取数据库中的模板消息id
    protected function _getTmpId(){
        $tmplModel = new tmplModel();
        $where = array(

        );
        $res = $tmplModel->getTmplList($where);
        $new = array();
        if(!empty($res)){

            foreach($res as $k=>$v){
                $new[$v['tmp_name']] = $v;
            }

        }
        return $new;
    }


    //检查是否登录
    protected function _checkLogin(){
        $controller = strtolower(CONTROLLER_NAME);//转成小写
        $action = strtolower(ACTION_NAME);//转成小写
        if(in_array($controller."/".$action, $this->no_need_login) || in_array($controller."/*", $this->no_need_login)){
            //当前控制器不需要登录
            //判断是不是登录控制器
            if($controller."/".$action == "login/index"){
                //当前是登录控制器,跳转到后台首页,判断有没有登录
                if(!empty($this->admininfo)){
                    header('Location:/admin/index/index');//去后台
                    exit;
                }
            }
            return true;
        }
        //当前控制器需要登录,检查是否已经登录
        if(empty($this->admininfo)){
            //没有登录
            header('Location:/admin/login/index');//去登陆
            exit;
        }else{
            //已经登录
            $this->_setMenus();
            return true;
        }
    }


    //根据uid获取用户信息
    public function getManagerInfobyUid($uid){
        $where = array(
            'adminuid' => $uid
        );
        $res = $this->managerModel->getManager($where);
        return $res;
    }


    //更新用户信息
    public function updateManagerInfo($uid,$data){
        $where = array(
            'adminuid' => $uid
        );
        $res = $this->managerModel->where($where)->save($data);
        return $res;
    }

    //刷新session userinfo
    public function updateManagerSession($uid){

        if(empty($uid)){
            return false;
        }

        $memberinfo = $this->getManagerInfobyUid($uid);
        session('admininfo',$memberinfo);
        $this->admininfo = $memberinfo;
        $this->assign('admininfo',$memberinfo);
    }

    //文件上传
    public function iupload($type="qrcode"){

        $upload = new \Think\Upload();
        $upload->rootPath  =  "/";
        $upload->savePath  = "/upload/".$type."/";
        $filrInfo   =   $upload->upload();
        if($filrInfo == false){
            $this -> error = $upload -> getError();
        }
        return $filrInfo;
    }
	
    public function excel($datastr,$header='',$excel_name=''){

        $filename = $excel_name.date('Y-m-d').'.csv'; //设置文件名
        header("Content-type:text/csv;charset=utf-8");
        header("Content-Disposition:attachment;filename=".$filename);
        header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
        header('Expires:0');
        header('Pragma:public');
        echo  $content = "\xEF\xBB\xBF".$header.$datastr; //添加BOM
    }
	
    protected function _setMenus () {
        $manager = $this->admininfo;
        if($manager['only_read']) {
            unset($_POST);
            unset($_FILES);
            if(IS_AJAX) {
                return_json(1,'你无权修改');
            }
        }
        $menuModel = $this->menuModel;
        $menuArr = $manager['menu'];
        $submenuArr = $manager['sub_menu'];
        $controller = strtolower(CONTROLLER_NAME);
        $action = strtolower(ACTION_NAME);//转成小写

        //顶部主菜单
        $menuWhere = array(
            'id'=>array('in',$menuArr),
            'level' => 1,
        );
        //侧面子菜单
        $subWhere = array(
            'level' => 2,
            'controller' => strtolower(CONTROLLER_NAME),
            'id' => array('in',$submenuArr),
        );
        //允许访问的菜单 验证权限
        $allowWhere = array(
            'id' => array('in',$submenuArr),
        );
        if($manager['is_super']) {
            unset($menuWhere['id']);
            unset($subWhere['id']);
            unset($allowWhere['id']);
        }
        $menu = $menuModel->getMenuList($menuWhere);

        foreach ($menu as $k=>$v) {
            $menu[$k]['url'] = "/admin/{$v['controller']}/{$v['action']}{$v['params']}";
        }
        $this->assign('MENU',$menu);


        $submenu = $menuModel->getMenuList($subWhere);
        $new = array();
        foreach ($submenu as $k=>$v){
            $v['url'] = "/admin/{$v['controller']}/{$v['action']}{$v['params']}";
            $new[$v['sub_id']]['menu'][] = $v;
            $new[$v['sub_id']]['title'] = $v['sub_title'];
        }
        $this->assign('SUBMENU',$new);

        $allow = false;

        $allowArr = $menuModel->getMenuList($allowWhere);
        $whiteArr = $this->_getWhiteArr();
        $allowArr = array_merge($allowArr,$whiteArr);
        foreach ($allowArr as $v){
            if($controller==$v['controller'] && $action==$v['action']){
                $allow = true;
            }
        }

        if(!$allow && $controller!='login') {
            if(IS_AJAX) {
                return_json(1,'你无权修改');
            }
            $this->error('无权访问');
        }
    }
	
    /*
     * 白名单 全部允许访问
     */
    protected function _getWhiteArr () {
        return array(
            array(
                'controller' => 'goods',
                'action' => 'uploadpic'
            ),
            array(
                'controller' => 'goods',
                'action' => 'getguigestock'
            ),
            array(
                'controller' => 'articlead',
                'action' => 'uploadpic'
            ),
            array(
                'controller' => 'article',
                'action' => 'uploadpic'
            ),
            array(
                'controller' => 'article',
                'action' => 'addarticle'
            ),
            array(
                'controller' => 'goods',
                'action' => 'addgoods'
            ),
            array(
                'controller' => 'member',
                'action' => 'edituserajax'
            ),
            array(
                'controller' => 'member',
                'action' => 'upload'
            ),
            array(
                'controller' => 'index',
                'action' => 'index'
            ),
            array(
                'controller' => 'system',
                'action' => 'getkeywords'
            ),
            array(
                'controller' => 'system',
                'action' => 'updatesucai'
            ),
            array(
                'controller' => 'system',
                'action' => 'getsucailist'
            ),
            array(
                'controller' => 'system',
                'action' => 'addkey'
            ),
            array(
                'controller' => 'system',
                'action' => 'createmenu'
            ),
            array(
                'controller' => 'system',
                'action' => 'getmenu'
            ),
            array(
                'controller' => 'order',
                'action' => 'setexpress'
            ),
            array(
                'controller' => 'order',
                'action' => 'wuliuajax'
            ),
            array(
                'controller' => 'finance',
                'action' => 'monthexcel'
            ),
            array(
                'controller' => 'finance',
                'action' => 'indexexcel'
            ),
            array(
                'controller' => 'member',
                'action' => 'memberpage'
            ),
            array(
                'controller' => 'member',
                'action' => 'memberexcel'
            ),
            array(
                'controller' => 'system',
                'action' => 'huandengpian'
            ),
            array(
                'controller' => 'member',
                'action' => 'getprovincelist'
            ),
            array(
                'controller' => 'member',
                'action' => 'getprovincechildren'
            )
        );
    }

}